import router from '@/router'
import { LOGIN } from '@/router/routeMap'
import { ElMessage } from 'element-plus'
import { removeToken } from '@/assets/js/auth'
import { ERROR_CODE } from '@/assets/js/const'
import useUserStore from '@/store/user'

export function requestErrorHandler(error) {
  console.error(error)
  const user = useUserStore()
  const code = error.code || 500
  const message = error.message || error

  ElMessage.error(message)
  if (code === ERROR_CODE.EXPIRED_TOKEN || code === ERROR_CODE.INVALID_TOKEN) {
    removeToken()
    user.isLogined = false
    router.push({ ...LOGIN, params: { redirect: router.currentRoute.value.fullPath } })
    return
  }
}
